package com.company.cloud.behavior.modules.app.controller;

import java.util.function.Function;

import com.company.cloud.behavior.modules.app.controller.req.FollowIsUserParam;
import com.company.cloud.behavior.modules.base.entity.UserFollowInfo;
import com.company.cloud.common.asserts.ValidatorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.behavior.modules.app.controller.req.FollowQuery4PageParam;
import com.company.cloud.behavior.modules.app.controller.req.FollowSaveParam;
import com.company.cloud.behavior.modules.base.entity.UserCollectionInfo;
import com.company.cloud.behavior.modules.base.service.UserCollectionInfoService;
import com.company.cloud.behavior.modules.cache.models.BehaviorSearchModel;
import com.company.cloud.behavior.modules.cache.service.BehaviorCacheService;
import com.company.cloud.behavior.modules.cache.utils.BehaviorConvertUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.log.annotation.SysLog;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 收藏
 */
@Login
@RestController
@RequestMapping("/app/behavior/collection")
@Api(tags = "App_Behavior_收藏服务")
public class CollectionController {

    @Autowired
    private UserCollectionInfoService userCollectionInfoService;

    @Autowired
    private BehaviorCacheService behaviorCacheService;

    @PostMapping("/query")
    @SysLog("收藏列表")
    @ApiOperation(value = "收藏列表查询", response = BehaviorSearchModel.class)
    public BaseResult query(@RequestBody FollowQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        IPage<UserCollectionInfo> page = userCollectionInfoService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<UserCollectionInfo>()
                        .eq("user_id", userInfo.getId())
                        .eq(CheckUtils.hasText(params.getObjType()), "obj_type", params.getObjType())
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                        .orderByDesc("cdt")
        );

        IPage<BehaviorSearchModel> data = page.convert(new Function<UserCollectionInfo, BehaviorSearchModel>() {
            @Override
            public BehaviorSearchModel apply(UserCollectionInfo entity) {
                BehaviorSearchModel model = BehaviorConvertUtils.getBehaviorSearchModel(entity);
                // 获取收藏对象
                model = behaviorCacheService.getRelInfo(model);
                return model;
            }
        });

        return BaseResult.ok(data);
    }


    @PostMapping("/save")
    @ApiOperation(value = "新增")
    public BaseResult save(@RequestBody FollowSaveParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        UserCollectionInfo collection = userCollectionInfoService.getOne(new QueryWrapper<UserCollectionInfo>()
                .eq("company_no", userInfo.getCompanyNo())
                .eq("user_id", userInfo.getId())
                .eq("obj_type", params.getObjType())
                .eq("obj_no", params.getObjNo())
                .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
        );
        if (collection != null) {
            return BaseResult.ok();
        }
        UserCollectionInfo entity = new UserCollectionInfo();
        entity.setCompanyNo(userInfo.getCompanyNo());
        entity.setUserId(userInfo.getId());
        entity.setObjType(params.getObjType());
        entity.setObjNo(params.getObjNo());
        entity.setObjIsUpdown(BaseConstant.YNEnum.YES.getCode());
        entity.addCreateParam(userInfo);
        userCollectionInfoService.save(entity);
        behaviorCacheService.updateCollectionCount(params.getObjType(), params.getObjNo(), 1);
        return BaseResult.ok(entity.getId());
    }


    @GetMapping("/delete")
    @ApiOperation(value = "删除")
    public BaseResult delete(@RequestParam("id") Integer id) {
        UserCollectionInfo entity = userCollectionInfoService.getById(id);
        if (null == entity || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        entity.setRowsState(BaseConstant.EnabledEnum.DISABLED.getCode());
        entity.addEditParam(userInfo);
        userCollectionInfoService.updateById(entity);
        behaviorCacheService.updateCollectionCount(entity.getObjType(), entity.getObjNo(), -1);
        return BaseResult.ok();
    }

    @PostMapping("/isCollected")
    @ApiOperation(value = "当前用户是否收藏", response = String.class)
    public BaseResult isCollected(@RequestBody FollowIsUserParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        UserCollectionInfo favorite = userCollectionInfoService.getOne(new QueryWrapper<UserCollectionInfo>()
                .eq("user_id", userInfo.getId())
                .eq("obj_type", params.getObjType())
                .eq("obj_no", params.getObjNo())
                .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
        );
        if (favorite != null) {
            return BaseResult.ok(BaseConstant.YNEnum.YES.getCode());
        }
        return BaseResult.ok(BaseConstant.YNEnum.NO.getCode());
    }

}
